package com.qizhou.compiler.enitity

import com.qizhou.compiler.BaseReposityClasType
import com.qizhou.compiler.aptUtils.logger.Logger
import com.qizhou.compiler.enitity.func.*
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import java.io.File
import javax.annotation.processing.Filer

/**
 * 生成 Reposity类
 */
class ReposityClassBuilder(val reposityClass: ReposityClass) {

    companion object {

        /**
         * 后缀
         */
        const val POSIX = "Reposity"
    }

    fun build(filer: Filer,outputPath:String) {
        val repClassName = getClassName()
        val fileBuilder = FileSpec.builder(reposityClass.packageName, repClassName)
        val typeBuilder = TypeSpec.classBuilder(repClassName)
                .addModifiers(KModifier.PUBLIC)
                .addModifiers(KModifier.OPEN)
                .superclass((BaseReposityClasType).parameterizedBy(reposityClass.serviceType))
                .addKdoc("This file is generated by kapt, please do not edit this file")
        startFuncBuid(typeBuilder)
        fileBuilder.addType(typeBuilder.build())

        fileBuilder.build().writeTo(File(outputPath))
    }

    private fun startFuncBuid(typeBuilder: TypeSpec.Builder) {
        reposityClass.fields.forEach {
            when (it::class.java) {
                DbCacheMethod::class.java -> {
                }
                SpCacheMethod::class.java -> {
                   SpCacheFunc(it as SpCacheMethod).build(typeBuilder)
                }
                AutoApiWithCacheMethod::class.java ->{
                    AutoApiWithCacheFunc(it as AutoApiWithCacheMethod).build(typeBuilder)
                }
                AutoMethod::class.java -> {
                    AutoApiFunc(it).build(typeBuilder)
                }
            }
        }
    }



    private fun getClassName(): String {
        val str = reposityClass.simpleName
        if (str.contains("Service")) {
            val strs = str.split("Service")
            if (strs.size > 1) {
                return strs[0] + POSIX
            }
        }
        return str
    }

}